<?php if (!defined("_ECRIRE_INC_VERSION")) return; if (class_exists('AlohacartExtension')) return;
/**
 * Aloha Cart
 *
 * @author     Aleksey Yaroshchuk (aleksey.yaroshchuk@gmail.com)
 * @license    GNU/GPL
 * @package    plugins
 * @subpackage alohacart
 * @copyright  (c) Aleksey Yaroshchuk 2011-2012
 * @link       http://www.spip-contrib.net/AlohaCart
 */

/** 
 *  This is base class for all extensions
 *
 *  @author Aleksey Yaroshchuk (aleksey.yaroshchuk@gmail.com)
 */
include_spip('functions/pdk_common');
//TODO: Change this class to PdkMetaModel (see PDK's todo)
/*abstract*/ class AlohacartExtension {
    /**
     *  Extension fields wich are stored in meta table
     */
    public $fields = array();
    
    /**
     *  Extension type (must be declared in child class)
     */
    public $type;
    
    /**
     *  Extension code (must be declared in child class)
     */
    public $code;
    
    /**
     *  Indicates whether extension is payable.
     *  If it is true, GetPayLink() method will return pay link, and if false, it will return empty string
     */
    public $isPayable = false;
    
    /**
     *  Alohacart
     */
    protected $cart;
	
	/**
     *  Ecatalogue CurrencyModel
     */
    protected $currency_mdl;
    
    /**
     *  AlohacartExtensionModel
     */
    protected $extension_mdl;
    
    public function __construct(){
        $this->validation = pdk_load_class('pdk_validation', 'classes');
        $this->cart = pdk_load_class('Alohacart','classes');
		$this->currency_mdl = pdk_load_class('CurrencyModel', 'classes');
        $this->extension_mdl = pdk_load_class('AlohacartExtensionModel', 'classes');
		include_spip('inc/filtres');
		include_spip('inc/texte');
    }
    
    /**
     *  Filters data array according to extension fields
     */
    public function FilterData($data) {
        $filtered_data = array(); 
        foreach ($data as $field=>$value) {
            if (in_array($field,array_values($this->fields)))
                $filtered_data[$field] = $value;
        }
        return $filtered_data;
    }
    
    /**
     *  Saves extension meta data to spip_meta table
     *  @param array $data Extension meta data
     */
    public function SaveMetaData($data=null) {        
        return ecrire_config("alohacart/".$this->type."_".$this->code, $data);
    }
    
    /**
     *  Gets extension meta data from spip_meta table          
     */
    public function GetMetaData() {        
        return lire_config("alohacart/".$this->type."_".$this->code);
    }
    
    /**
     *  Gets extension cost in main currency
     */
    public function GetCost() { 		
		return 0;
	}
	
	/**
     *  Modifies extension cost:
	 *  - If cart cost is more than free from price of extension, cost will be changed to 0
	 *
	 *	@param float $cost Cost in main currency
	 *  @param array $meta_data Meta data of extension. If it isn't defined, meta data of current extension will be get
	 *  @return float Modified price in main currency 
     */
	protected function ModifyCost($cost = 0, $meta_data = array()) {
		if (!$meta_data)
			$meta_data = $this->GetMetaData();
		
		if (isset($meta_data['free_from']) && $meta_data['free_from']) {
			// If extension has it's own currency, convert free_from price from this currency into current currency
			if (isset($meta_data['id_currency']))
				$free_from = $this->currency_mdl->ConvertPrice($meta_data['free_from'], $meta_data['id_currency'], $this->currency_mdl->GetCurrentCurrencyId());
			// otherwise convert free_from price from main currency into current currency
			else 
				$free_from = $this->currency_mdl->ConvertPrice($meta_data['free_from'], $this->currency_mdl->GetMainCurrencyId(), $this->currency_mdl->GetCurrentCurrencyId());
			
			if ($this->cart->CountPrice() >= $free_from)
				$cost = 0;
		}
		
		return $cost;	
	}
    
    /**
     *  Modifies extension's data
     *  - If extension has free_from, cost will be changed to 0
     */
    protected function ModifyData($data = '', $meta_data = array()) {
        if (!$meta_data)
			$meta_data = $this->GetMetaData();
        
        $free_from = $this->GetFreeFromCost();
        if ($free_from) {
            $free_from = $this->currency_mdl->ConvertPriceToCurrentCurrency($free_from);
            $currency = $this->currency_mdl->GetCurrentCurrency();
            $data .= _T('alohacart:free_from').' '.extraire_multi($currency['sign_pre']).' '.$free_from.' '.extraire_multi($currency['sign_after']);
        }
            
        return $data;
    } 
	
	/**
	 *  Gets free from cost in main currency
	 */
	public function GetFreeFromCost() {
		$data = $this->GetMetaData();
		$cost = isset($data['free_from'])?$data['free_from']:0;
		if ($data['id_currency'])
            $cost = $this->currency_mdl->ConvertPriceToMainCurrency($cost, $data['id_currency']);
		return $cost;	
	}
    
    /**
     *  Gets extension data (info) wich is outputed for user
     *  @param array $options Array of additional options, needed for extension, e.g. id_order
     */
    public function GetData($options=array()){ return '';}
    
    /**
     *  Gets pay link
     *  @param int $id_order ID order for wich payment will be held
     */
    public function GetPayLink($id_order) {
        if (!$this->isPayable) return '';
        if (!$id_order) return '';
        $extension = $this->extension_mdl->select("code='".mysql_real_escape_string($this->code)."'");
        if (!$extension[0]) return '';
        $extension = $extension[0];
        
        $text = _T('alohacart_payment_'.$this->code.':pay');
        if (!$text) $text = _T('alohacart:pay');
        
        return '<a target="_blank" href="'.$GLOBALS['meta']['adresse_site'].'/?page=alohacart_user&url=payform_auto&id_extension='.$extension['id_extension'].
                '&id_order='.$id_order.'&var_mode=calcul">'.$text.'</a>';
    }
    
    /**
     *  Does needed operations after successfully payment operation
     *  @param int $id_order ID of order wich was payed
     *  @param array Additional data that can be used to update order after payment. For example, request data from payment system.
     */ 
    public function PaymentSuccess($id_order = '', $data = array()) {
        $meta_data = $this->GetMetaData();
        $id_order_statut_after_payment = isset($meta_data['id_order_statut_after_payment'])?$meta_data['id_order_statut_after_payment']:''; 
        if ($id_order_statut_after_payment && $id_order) {
            $order_mdl = pdk_load_class('AlohacartOrderModel', 'classes');
            $order_data['id_statut'] = $id_order_statut_after_payment;
            if ($payment_data = $this->CreatePaymentData($data))
                $order_data['payment_data'] = $payment_data;
            $order_mdl->update_by_id($id_order, $order_data);
			// Notify about success payment
			$this->NotifyAboutPaymentSuccess($id_order);
        }
    }
	
	/**
     *  Notifies admin and user about success payment
	 *  @param int $id_order ID of payed order
     */
	public function NotifyAboutPaymentSuccess($id_order) {
		$sender = pdk_load_class('PdkPHPMailerSender', 'classes/mail');
		$order_mdl = pdk_load_class('AlohacartOrderModel', 'classes');		
		
		$order = $order_mdl->select_by_id($id_order);
		if (!$order) return false;
		
        $email_to = lire_config('alohacart/orders_emails');
		$email_to = str_replace(' ', '', $email_to);
		$email_to = explode(',',$email_to);
		
		$sender_email = $GLOBALS['meta']['email_webmaster'];
		if (!$sender_email) $sender_email = 'no-reply@'.$_SERVER["SERVER_NAME"];
			
		$options = array('from_email' => $sender_email, 'from_name'=>supprimer_tags(typo($GLOBALS['meta']['nom_site'])));
		$subject = _T('alohacart:payment_notify_subject', array('payment_system'=>extraire_multi($order['payment_titre']), 
			'nom_site_spip'=>supprimer_tags(typo($GLOBALS['meta']['nom_site']))));		
		
		// Notify admin
		if ($email_to) {			
			$message = recuperer_fond('inc/emails/payment_notify_admin', array('order'=>$order));
			$sender->Send($email_to, $subject, $message, $options);
		}
		
		// Notify user
		if ($order['email']) {
			$message = recuperer_fond('inc/emails/payment_notify_user', array('order'=>$order));
			$sender->Send($email_to, $subject, $message, $options);
		}
	}
    
    /**
     *  Creates payment text data (info), that can be written into DB orders table
     *  @param array $data Array of data, from wich payment data will be created 
     */
    public function CreatePaymentData($data) {}
}
?>